package com.ctrip.demo.threadpool;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

public class ThreadChangeDemo {

    public static void main(String[] args) throws InterruptedException {
        dynamicModifyExecutor();
    }

    private static ThreadPoolExecutor buildThreadPoolExecutor() {
        return new ThreadPoolExecutor(
                2,
                5,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10),
                Executors.defaultThreadFactory());
    }

    private static void dynamicModifyExecutor() throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = buildThreadPoolExecutor();
        for (int i = 0; i < 15; i++) {
            threadPoolExecutor.submit(() -> {
                threadPoolStatus(threadPoolExecutor, "创建任务");
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        threadPoolStatus(threadPoolExecutor, "改变之前");
        threadPoolExecutor.setCorePoolSize(10);
        threadPoolExecutor.setMaximumPoolSize(10);
        threadPoolExecutor.prestartAllCoreThreads();
//        ResizableCapacityLinkedBlockingDeque<Runnable> queue = (ResizableCapacityLinkedBlockingDeque<Runnable>) threadPoolExecutor.getQueue();
//        queue.setCapacity(100);
        threadPoolStatus(threadPoolExecutor, "改变之后");
        Thread.currentThread().join();
    }

    private static void threadPoolStatus(ThreadPoolExecutor threadPoolExecutor, String name) {
        LinkedBlockingDeque<Runnable> queue = (LinkedBlockingDeque<Runnable>) threadPoolExecutor.getQueue();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ": " + Thread.currentThread().getName() + "-" + name + "-:" +
                "核线程数：" + threadPoolExecutor.getCorePoolSize() +
                "活动线程数：" + threadPoolExecutor.getActiveCount() +
                "最大线程数：" + threadPoolExecutor.getMaximumPoolSize() +
                "线程池活跃度：" + threadPoolExecutor.getCorePoolSize() +
                "任务完成数：" + divide(threadPoolExecutor.getActiveCount(), threadPoolExecutor.getMaximumPoolSize())+
                "队列大小：" + (queue.size() + queue.remainingCapacity()) +
                "当前排队线程数：" + queue.size() +
                "队列剩余大小：" + queue.remainingCapacity() +
                "队列使用度：" + divide(queue.size(), queue.size() + queue.remainingCapacity()) );

        System.out.println(System.getProperty("file.encoding"));
    }

    private static String divide(int num1, int num2) {
        return String.format("%1.2f%%",
                Double.parseDouble(num1 + "") / Double.parseDouble(num2 + "") *100);
    }

}
